<?php

namespace App\Http\Controllers\Admin;

use App\Models\Article;
use App\Repositories\PicturesRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticlesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::orderBy('created_at', 'asc')->paginate(20);

        return view('article.index', compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('article.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $res = Article::create($request->all());
        if($res){
            $data = array(
                'status' => 1,
                'data' => null,
                'msg' => '提交成功!'
            );
        }else{
            $data = array(
                'status' => 0,
                'data' => null,
                'msg' => '提交失败!'
            );
        }
        return json_encode($data);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $article = Article::findOrFail($id);
//        dump($article->toArray());
        return view('article.edit', compact('article'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $article = Article::findOrFail($id);
        $res = $article -> update($request -> all());
        if($res)
        {
            $data = array(
                'status' => 1,
                'data' => null,
                'msg' => '修改成功'
            );
        }
        else
        {
            $data = array(
                'status' => 0,
                'data' => null,
                'msg' => '修改失败'
            );
        }

        return json_encode($data);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 通过网址去获得文章内容
     */
    public function getArticle()
    {
        $link = stripslashes(trim($_GET['url']));
        $link = str_replace('https', 'http', $link);
        $html = $this -> get_contents($link);
        $html = str_replace('data-src','src',$html);
        preg_match("/<h2 class=\"rich_media_title\" id=\"activity-name\">([\s\S]*?)<\/h2>/", $html, $match_title);
        preg_match("/id=\"post-user\">([\s\S]*?)<\/a>/", $html, $match_gongzhonghao);
        preg_match("/<div class=\"rich_media_content \" id=\"js_content\">([\s\S]*?)<\/div>/", $html, $match_content);
        if(count($match_title)>0){
            $title = trim($match_title[1]);
        }else{
            $title = '';
        }
        if(count($match_gongzhonghao)>0){
            $gongzhonghao = $match_gongzhonghao[1];
        }else{
            $gongzhonghao = '';
        }
        if(count($match_content)>0){
            $content = str_replace('<script nonce="MOONSAFE_NONCE"','',$match_content[1]);
            $content = str_replace("'",'&rsquo;',$content);
            $content = str_replace("preview.html",'player.html',$content);
            $content = str_replace("<pre",'<div',$content);
            $content = str_replace("pre>",'div>',$content);
            $content = preg_replace("/&width=(.*?)&height=(.*?)&auto=0/is", "", $content);
        }else{
            $content = '';
        }
        if($content){
            $data = array(
                'status' => 1,
                'data' => array(
                    'title' => $title,
                    'author' => $gongzhonghao,
                    'content' => trim($content)
                ),
                'msg' => 'success'
            );
        }else{
            $data = array(
                'status' => 0,
                'data' => null,
                'msg' => '请输入正确的地址'
            );
        }
//        echo trim($content);
        return json_encode($data);

    }

    public function get_contents($url)
    {
        if (function_exists('curl_init')) {
            $ch = curl_init();
            $timeout = 100;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_TIMEOUT, 2);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        } else {
            $file_contents = file_get_contents($url);
        }
        return $file_contents;
    }

    public function upload(Request $request){
        $file = $request->file('files');
        $pic = app()->build(PicturesRepository::class);
        $res = $pic->uploadByHash($file,"article",null,null);

//        dd($res->toArray());

//        $name = $file->hashName();
//        $save_name = 'article/'.$name;
//        $res = Storage::disk('oss')->put($save_name, file_get_contents($file->path()));
//        $path = "http://aichacha.oss-cn-shanghai.aliyuncs.com/".$save_name;
        if($res['url']!=''&&$res['url']!=null){
            $data = array(
                'status' => 1,
                'data' => $res['url'],
                'msg' => 'success'
            );
        }else{
            $data = array(
                'status' => 0,
                'data' => null,
                'msg' => '图片上传失败!'
            );
        }
        return json_encode($data);
    }

}
